package network

import (
	_ "GameServer/conf"
	_ "GameServer/pb"
	rpc_world "GameServer/pb/rpc_world"
	_ "errors"
	_ "fmt"
	"time"

	"GameServer/common/logger"
	"GameServer/conf"
	_ "GameServer/libs/glog"
	_ "github.com/golang/protobuf/proto"
	_ "golang.org/x/net/context"
	context "golang.org/x/net/context"
	"google.golang.org/grpc"
)

var (
	cf_rpc       *grpc.ClientConn
	cf_addr      = "localhost:50051"
	world_rpc    *grpc.ClientConn
	world_client rpc_world.RoomClient
)

func InitRPC() error {
	var err error
	if len(conf.GetWorldRPCAddr()) != 0 {
		world_rpc, err = grpc.Dial(conf.GetWorldRPCAddr(), grpc.WithInsecure(), grpc.WithTimeout(time.Duration(3)*time.Second))
		if err != nil {
			logger.Notic("dail world rpc addr:%v failed:%v", conf.GetWorldRPCAddr(), err)
			return err
		}
		logger.Info("init world rpc connection success! addr:%v", conf.GetWorldRPCAddr())
		world_client = rpc_world.NewRoomClient(world_rpc)
	}
	return err
}

func DoRPC() {
	//todo: 参数，返回值细化
}

func DoRPCCreateRoom(playerid int32, createname string) *rpc_world.CreateRoomReply {
	var req rpc_world.CreateRoomRequest
	req.CreatePlayerId = playerid
	req.CreatorName = createname

	return RPCCreateRoom(&req)
}

func RPCCreateRoom(req *rpc_world.CreateRoomRequest) *rpc_world.CreateRoomReply {
	if world_rpc == nil {
		return nil
	}
	logger.Info(" create room rpc req:%+v", req)
	r, err := world_client.CreateRoom(context.Background(), req)
	if err != nil {
		logger.Notic("error do create room rpc failed:%v", err)
		return nil
	}
	logger.Info("create room rpc resp:%+v", r)
	return r
}
